package com.suning.generator.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.suning.generator.util.NotifyUtils;
import org.jetbrains.annotations.NotNull;

/**
 * 父Action类
 * 共用的逻辑封装
 *
 * @author bail
 * @date 2020/5/7
 */
public abstract class BaseAction extends AnAction {

    @Override
    public void update(@NotNull AnActionEvent e) {
        super.update(e);
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        Project project = e.getData(CommonDataKeys.PROJECT);
        PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
        e.getPresentation().setEnabled(
                editor != null && project != null && psiFile instanceof PsiJavaFile
        );
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Editor editor = e.getData(CommonDataKeys.EDITOR);
        Project project = e.getData(CommonDataKeys.PROJECT);
        PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
        if (editor == null || project == null || !(psiFile instanceof PsiJavaFile)) {
            return;
        }

        // 转换为javaFile,并获取PsiClass
        PsiJavaFile psiJavaFile = (PsiJavaFile) psiFile;
        final PsiClass[] classes = psiJavaFile.getClasses();
        if (classes.length <= 0) {
            NotifyUtils.notifyMessage(project, "抱歉, 该文件无法生成单元测试");
            return;
        }
        doCommand(classes[0], project);
    }

    /**
     * 处理命令后续操作
     */
    public abstract void doCommand(PsiClass psiClass, Project project);

}
